/**
 * 数字教材DAT文件加密
 *
 * 需要安装以下依赖:
 * npm install aes-js jszip
 */

const fs = require('fs');
const path = require('path');
const aes = require('aes-js');
const JSZip = require('jszip');
const toolsNode = require('../libs/tools-node');
const KEY256 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31];

// 获取传递给脚本的参数（排除前两个默认参数）
const args = process.argv.slice(2);
let from = args[0];

let zip = new JSZip()
fs.readdirSync(from).forEach((fileName) => {
  let filePath = path.join(from, fileName);
  let fileContent = fs.readFileSync(filePath);
  zip.file(fileName, fileContent.toString());
});
zip.generateAsync({
  type: 'nodebuffer',
  compression: 'DEFLATE'
}).then((content) => {
  let aesCtr = new aes.ModeOfOperation.ctr(KEY256)
  let encryptedBytes = aesCtr.encrypt(content)
  let toPath = `${from}.dat`
  toolsNode.writeFileSync(toPath, encryptedBytes);
});
